package org.zanpu.metadataserver.core.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.zanpu.metadataserver.api.util.TableEnum;
import org.zanpu.metadataserver.core.bpm.service.BpmService;
import org.zanpu.metadataserver.core.dbmanager.InsertVo;
import org.zanpu.metadataserver.core.metadata.service.MetadataService;
import org.zanpu.metadataserver.core.util.ValuesUtil;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Created by MD on 2016/11/4.
 */
@Controller
@RequestMapping("/metadataDB")
public class MetadataDBController extends ControllerUtilities {

    @Resource
    private MetadataService metadataService;

    @Resource
    private BpmService bpmService;

    /**
     * 更新数据表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateTable/{baseId}")
    public int updateTable(@PathVariable int baseId) {
        try {
            switch (baseId) {
                case 3:
                    String sql = "delete from " + TableEnum.META_DATA_TABLE.getName() + " WHERE base_id=" + baseId;
                    metadataService.delete(sql);
                    metadataService.queryTable().stream().map(table ->
                                    InsertVo.build(TableEnum.META_DATA_TABLE.getName(), "null," + quotes + table + quotes + comma + baseId)
                    ).forEach(metadataService::insert);
                    break;
            }
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
    }


    /**
     * 更新数据字典表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateDictionary", method = RequestMethod.POST, consumes = "application/text;charset=UTF-8")
    public int updateDictionary(@RequestBody String jsonStr) {
        try {
            Map<String, Object> jsonMap = jsonStrToMap(jsonStr);
            String sql = "delete from " + TableEnum.META_DATA_DICTIONARY.getName() + " WHERE table_id=" + jsonMap.get("table_id");
            metadataService.delete(sql);
            metadataService.queryColumns(quotes + jsonMap.get("dictionary_table") + quotes).stream().map(column ->
                            InsertVo.build(TableEnum.META_DATA_DICTIONARY.getName(),
                                    ValuesUtil.insertValues(ValuesUtil.putAll(column, jsonMap)))
            ).forEach(metadataService::insert);
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }

    }
}
